package com.ygsoft.tianlu_mall.controller;

import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygsoft.tianlu_mall.pojo.Msg;
import com.ygsoft.tianlu_mall.pojo.vo.req.AddGoodsReqVO;
import com.ygsoft.tianlu_mall.pojo.vo.req.DoRealReqVO;
import com.ygsoft.tianlu_mall.pojo.vo.req.UpdateGoodsReqVO;
import com.ygsoft.tianlu_mall.service.MessageService;
import com.ygsoft.tianlu_mall.service.NumService;
import com.ygsoft.tianlu_mall.service.ShopService;
import com.ygsoft.tianlu_mall.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.*;

@Controller
public class ShopController {

    @Autowired
    private ShopService shopService;

    @Autowired
    NumService numService;

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserRoleService userRoleService;

    //检查用户是否已经实名制验证
    //isReal： 0未实名认证 1已经实名认证
    @RequestMapping(value = "/checkIsRealName",method = RequestMethod.GET)
    @ResponseBody
    public Msg checkRealName(@RequestParam int user_id){
        int isReal = shopService.checkRealName(user_id);
        HashMap<String,Object> result = new HashMap<>();
        if (isReal==0){
            String message = "您还没通过实名认证，请先通过实名认证！";
            result.put("message",message);
            result.put("isReal",isReal);
            return Msg.fail().add("result",result);
        }else {
            result.put("isReal",isReal);
            return Msg.succes().add("isReal",isReal);
        }
    }

    //实名认证
    @RequestMapping(value = "/doReal",method = RequestMethod.PUT)
    @ResponseBody
    public Msg doReal(@RequestBody DoRealReqVO vo){
        try {
            shopService.doReal(vo);
            messageService.doreal(vo.getUser_id());
            return Msg.succes().add("user_id",vo.getUser_id());
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //管理员查看信息
    @RequestMapping(value = "/getRealInfo",method = RequestMethod.GET)
    @ResponseBody
    public Msg getRealInfo(@RequestParam int user_id){
        try {
            HashMap<String,Object> realInfo = shopService.getRealInfo(user_id);
            return Msg.succes().add("result",realInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //开店
    @RequestMapping(value = "/openShop",method = RequestMethod.POST)
    @ResponseBody
    public Msg openShop(@RequestParam int user_id,
                        @RequestParam String shop_name,
                        @RequestParam int user_shop){
        try {
            HashMap<String,Object> result = new HashMap<>();
            if (user_shop==1){
                shopService.openShop(user_id,shop_name);
                userRoleService.openShop(user_id);
                int shop_id = shopService.getShopIdByUserId(user_id);
                result.put("user_id",user_id);
                result.put("shop_id",shop_id);
                return Msg.succes().add("result",result);
            }else {
                String message = "您没权限开店，请先通过实名制!";
                return Msg.fail().add("message",message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //添加商品到店铺
    @RequestMapping(value = "/setGoods",method = RequestMethod.POST)
    @ResponseBody
    public Msg addGoods(@RequestBody AddGoodsReqVO vo){
        /*
        json格式
    {
        "goods_name":"后台管理界面-工作云管家",
        "goods_price":28,
        "goods_description":"后台管理界面-工作云管家 的描述",
        "shop_id":1,
        "type_id":1,
        "propertyValueItemReqVOList":[
            {
                "property_id":1,
                "propertyValue_name":"value1"
            },
            {
                "property_id":2,
                "propertyValue_name":"value2"
            },
            {
                "property_id":3,
                "propertyValue_name":"value3"
            },
            {
                "property_id":4,
                "propertyValue_name":"value4"
            }
        ]
    }
    */
        try {
            shopService.addGoods(vo);
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //上传文件到阿里云并保存链接到数据库
    @RequestMapping(value = "/setGoodsTitle",method = RequestMethod.POST)
    @ResponseBody
    public Msg setGoodsTitle(@RequestParam MultipartFile title, @RequestParam int shop_id, @RequestParam int type_id ) {
        try {
            String bucketName = "xdeer-mall";
            //获得当前商品id
            int goods_id = shopService.getNewGoodId();
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //构建上传目录
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            //文件上传到阿里云
            String titleName = folder + title.getOriginalFilename();
            try {
                ossClient.putObject(bucketName,titleName,title.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            URL titleUrl  =ossClient.generatePresignedUrl(bucketName,titleName,expiration);
            shopService.saveGoodsTitleUrl(goods_id,titleUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }
    @RequestMapping(value = "/setGoodsContent",method = RequestMethod.POST)
    @ResponseBody
    public Msg setGoodsContent(@RequestParam MultipartFile content, @RequestParam int shop_id, @RequestParam int type_id ) {
        try {
            String bucketName = "xdeer-mall";
            //获得当前商品id
            int goods_id = shopService.getNewGoodId();
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //构建上传目录
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            //文件上传到阿里云
            String contentName = folder + content.getOriginalFilename();
            try {
                ossClient.putObject(bucketName,contentName,content.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            URL contentUrl  =ossClient.generatePresignedUrl(bucketName,contentName,expiration);
            shopService.saveGoodsContentUrl(goods_id,contentUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }
    @RequestMapping(value = "/setGoodsFile",method = RequestMethod.POST)
    @ResponseBody
    public Msg setGoodsFile(@RequestParam MultipartFile file, @RequestParam int shop_id, @RequestParam int type_id ) {
        try {
            String bucketName = "xdeer-mall";
            //获得当前商品id
            int goods_id = shopService.getNewGoodId();
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //构建上传目录
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            //文件上传到阿里云
            String fileName = folder + file.getOriginalFilename();
            try {
                ossClient.putObject(bucketName,fileName,file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            URL fileUrl  =ossClient.generatePresignedUrl(bucketName,fileName,expiration);
            shopService.saveGoodsFileUrl(goods_id,fileUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }


    //上架商品
    //商品状态 0 待上架 1上架 2 上架
    @RequestMapping(value = "/goodsUpshelf",method = RequestMethod.PUT)
    @ResponseBody
    public Msg goodsUpshelf(@RequestParam int goods_id){
        try {
            //检查商品是否被添加
            if (!shopService.checkGoodsOnDB(goods_id)) {
                String message = "你所上架的商品并未添加到店铺里！";
                return Msg.fail().add("message",message);
                //检查商品的状态
            }else if (shopService.checkGoodsStatus(goods_id)==1){
                String message = "你所上架的商品已经处于上架状态，无需重复上架！";
                return Msg.fail().add("message",message);
            }else {
                shopService.goodsUpshelf(goods_id);
                return Msg.succes();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //下架商品
    @RequestMapping(value = "/goodsDownshelf",method = RequestMethod.PUT)
    @ResponseBody
    public Msg deleteOneGoods(@RequestParam("goods_id") int goods_id){
        try {
            if (!shopService.checkGoodsOnDB(goods_id)){
                String message = "你所下架的商品并未添加到店铺里！";
                return Msg.fail().add("message",message);
                //检查商品的状态
            }else if (shopService.checkGoodsStatus(goods_id)==2){
                String message = "你所下架的商品已经处于下架状态，无需重复下架！";
                return Msg.fail().add("message",message);
            }else {
                shopService.goodsDownshelf(goods_id);
                return Msg.succes();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //根据商品id获取填充更新框内的信息
    @RequestMapping(value = "/getUpdateGoodsInfo",method = RequestMethod.GET)
    @ResponseBody
    public Msg getUpdateGoodsInfo(@RequestParam int goods_id){
        try {
            if (!shopService.checkGoodsOnDB(goods_id)){
                String message = "你所更新的商品并未添加到店铺里！";
                return Msg.fail().add("message",message);
            }else {
                HashMap<String, Object> updateGoodsInfo= shopService.getUpdateGoodsInfo(goods_id);
                Map<Object,Object> result = new HashMap<>();
                result.put("updateGoodsInfo",updateGoodsInfo);
                return Msg.succes().add("result",result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //修改商品信息
    @RequestMapping(value = "/updateGoodsInfo",method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateGoods(@RequestBody UpdateGoodsReqVO vo){
    /*
    json格式
    {
        "goods_id" : 52,
        "goods_name" : "测试更新",
        "goods_price" : 200,
        "goods_description" : "测试描述更新",
        "goods_updateLog" : "测试更新日志",
        "propertyValueItemReqVOList":[
            {"property_id":5,
                    "propertyValue_name":"value5测试更新"
            },
            {"property_id":6,
                    "propertyValue_name":"value6测试更新"
            },
            {"property_id":7,
                    "propertyValue_name":"value7测试更新"
            },
            {"property_id":8,
                    "propertyValue_name":"value8测试更新"
            }
        ]
    }
* */
        try {
            shopService.updateGoods(vo);
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //更新文件到阿里云并保存最新链接到数据库
    //请求方法不能为PUT
    //报错：HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
    @RequestMapping(value = "/updateGoodsTitle",method = RequestMethod.POST)
    @ResponseBody
    public Msg updateGoodsTitle(@RequestParam MultipartFile title, @RequestParam int goods_id) {
        try {
            String bucketName = "xdeer-mall";
            int type_id = shopService.getTypeId(goods_id);
            int shop_id = shopService.getShopId(goods_id);
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String titleName = folder + title.getOriginalFilename();
            //文件上传
            try {
                ossClient.putObject(bucketName,titleName,title.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取url链接
            URL titleUrl  =ossClient.generatePresignedUrl(bucketName,titleName,expiration);
            //更新url链接
            HashMap<String,Object> urlMap = new HashMap<>();
            urlMap.put("goods_id",goods_id);
            urlMap.put("titleUrl",titleUrl.toString());
            shopService.updateGoodsTitleUrl(goods_id,titleUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }
    @RequestMapping(value = "/updateGoodsContent",method = RequestMethod.POST)
    @ResponseBody
    public Msg updateGoodsContent(@RequestParam MultipartFile content, @RequestParam int goods_id) {
        try {
            String bucketName = "xdeer-mall";
            int type_id = shopService.getTypeId(goods_id);
            int shop_id = shopService.getShopId(goods_id);
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String contentName = folder + content.getOriginalFilename();
            //文件上传
            try {
                ossClient.putObject(bucketName,contentName,content.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }

            //获取url链接
            URL contentUrl  =ossClient.generatePresignedUrl(bucketName,contentName,expiration);
            //更新url链接
            HashMap<String,Object> urlMap = new HashMap<>();
            urlMap.put("goods_id",goods_id);
            urlMap.put("contentUrl",contentUrl.toString());
            shopService.updateGoodsContentUrl(goods_id,contentUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }
    @RequestMapping(value = "/updateGoodsFile",method = RequestMethod.POST)
    @ResponseBody
    public Msg updateGoodsFile(@RequestParam MultipartFile file, @RequestParam int goods_id) {
        try {
            String bucketName = "xdeer-mall";
            int type_id = shopService.getTypeId(goods_id);
            int shop_id = shopService.getShopId(goods_id);
            String type_name = shopService.getFolderName(type_id);
            String shop_name = shopService.getShopName(shop_id);
            String goods_name = shopService.getGoodsName(goods_id);
            String folder = type_name + "/" +  shop_name + "/" + goods_name + "/";
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String fileName = folder + file.getOriginalFilename();
            //文件上传
            try {
                ossClient.putObject(bucketName,fileName,file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取url链接
            URL fileUrl  =ossClient.generatePresignedUrl(bucketName,fileName,expiration);
            //更新url链接
            HashMap<String,Object> urlMap = new HashMap<>();
            urlMap.put("goods_id",goods_id);
            urlMap.put("fileUrl",fileUrl.toString());
            shopService.updateGoodsFileUrl(goods_id,fileUrl.toString());
            return Msg.succes();
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }


    //查看店铺商品（所有）
    @RequestMapping(value = "/getShopGoods",method = RequestMethod.GET)
    @ResponseBody
    public Msg getShopGoods(@RequestParam int shop_id){
        try {
            List<HashMap<String,Object>> goodsNum = new ArrayList<>();
            Map<Object,Object> result = new HashMap<>();
            List<Map<String,Object>> goodsList =  shopService.getGoodsByShopId(shop_id);
            List goods_idList = shopService.getGoodsIdByShopId(shop_id);
            for (Object goods_id:goods_idList){
                HashMap<String,Object> goodsNumMap =numService.getThreeNum((int)goods_id);
                goodsNum.add(goodsNumMap);
            }
            result.put("goodsNum",goodsNum);
            result.put("goodsList",goodsList);
            return Msg.succes().add("result",result);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

    //根据类型查看店铺商品
    @RequestMapping(value = "/getShopGoodsByType",method = RequestMethod.GET)
    @ResponseBody
    public Msg getShopGoodsByType(@RequestParam int shop_id,
                                  @RequestParam int type_id,
                                  @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                  @RequestParam Integer pageSize){
        try {
            List<HashMap<String,Object>> goodsNum = new ArrayList<>();
            Map<Object,Object> result = new HashMap<>();
            PageHelper.startPage(pageNum,pageSize);
            List<Map<String,Object>> goodslist =  shopService.getGoodsByShopIdAndTypeId(shop_id,type_id);
            PageInfo goodsList = new PageInfo(goodslist,5);
            List goods_idList = shopService.getGoodsIdByShopIdAndTypeId(shop_id,type_id);
            for (Object goods_id:goods_idList){
                HashMap<String,Object> goodsNumMap =numService.getThreeNum((int)goods_id);
                goodsNum.add(goodsNumMap);
            }
            result.put("goodsNum",goodsNum);
            result.put("goodsList",goodsList);
            return Msg.succes().add("result",result);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }



    //获取商品评分
    @RequestMapping(value = "/getShopScore",method = RequestMethod.GET)
    @ResponseBody
    public Msg getShopScore(@RequestParam int shop_id){
        Map<Object,Object> result = new HashMap<>();
        String shop_name = shopService.getShopName(shop_id);
        Double service = shopService.getService(shop_id);
        Double description = shopService.getDescription(shop_id);
        result.put("shop_id",shop_id);
        result.put("shop_name",shop_name);
        result.put("service",service);
        result.put("description",description);
        return Msg.succes().add("result",result);
    }

    //用户是否收藏了店铺
    //isCollect 0未收藏 1已收藏
    @RequestMapping(value = "/userIsCollectShop",method = RequestMethod.GET)
    @ResponseBody
    public Msg userIsCollectShop(@RequestParam int shop_id,@RequestParam int user_id){
        Map<Object,Object> result = new HashMap<>();
        int isCollect = shopService.isCollectShop(shop_id,user_id);
        result.put("shop_id",shop_id);
        result.put("shop_name",shopService.getShopName(shop_id));
        result.put("isCollect",isCollect);
        return Msg.succes().add("result",result);
    }

}
